<template>
  <div class="budgetDelivery">
    <div class="contentTopTitle">
      <div class="fl">
        <div class="title">预算下达</div>
      </div>
      <div class="fr">
        <el-button
          @click="
            $router.push({
              path: '/budget/budgetDeliveryRecord',
              query: {
                areaId: form.areaSelect.areaId,
                areaLvl: form.areaSelect.areaLvl,
                areaName: form.areaSelect.areaName,
              },
            })
          "
          size="small"
          >下达记录</el-button
        >
      </div>
    </div>
    <div>
      <el-form :inline="true" :model="form" label-width="70px" class="formList">
        <el-form-item label="预算年度">
          <el-date-picker
            v-model="form.year"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
            @change="changeYear"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="区域">
          <dx-cascader
            :area_id.sync="form.areaSelect.areaId"
            :area_lvl.sync="form.areaSelect.areaLvl"
            :area_name.sync="form.areaSelect.areaName"
            ref="cascader"
          />
        </el-form-item>
        <el-form-item label="指标类型">
          <el-select v-model="form.indexType" placeholder="请选择" clearable>
            <el-option
              v-for="item in indexTypeOptions"
              :key="item.key"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-buttons">
          <div>
            <el-button size="small" type="primary" @click="search"
              >查询</el-button
            >
          </div>
          <div>
            <el-button size="small" @click="exportModal">模版下载</el-button>
          </div>

          <el-upload
            class="upload-demo"
            action="/api/releaseSecond/importNewEditData"
            :limit="3"
            :data="params"
            :on-success="importTarget"
            :on-progress="progress"
            :on-error="errorUpload"
            :show-file-list="false"
            v-if="isDelete != 0"
          >
            <el-button size="small" type="warning">导入</el-button>
          </el-upload>
          <div>
            <el-button size="small" type="warning" disabled v-if="isDelete == 0"
              >导入</el-button
            >
          </div>

          <!-- <div>
            <el-button size="small"
                     type="primary"
                     @click="doRelease"
                     :disabled="isDelete == 0">下达</el-button>
          </div> -->

          <div>
            <el-button
              size="small"
              type="warning"
              @click="exportData"
              :disabled="isDelete == 0"
              >导出</el-button
            >
          </div>
          <div>
            <el-button
              size="small"
              type="warning"
              @click="exportDataAll"
              :disabled="isDelete == 0"
              >批量导出</el-button
            >
          </div>
          <div>
            <el-button
              size="small"
              type="warning"
              @click="refreshDialogVisible = true"
              >刷新</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="tableBox">
      <el-table
        :data="tableData"
        border
        height="75vh"
        :empty-text="emptyText"
        style="width: 100%"
      >
        <el-table-column
          prop="indexName"
          label="指标名称"
          width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="indexType" label="指标类型" width="140">
        </el-table-column>
        <el-table-column prop="areaName" width="100" label="区域名称">
        </el-table-column>
        <el-table-column
          prop="annual"
          label="全年"
          width="110"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="oneQuarter"
          width="100"
          label="一季度"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="twoQuarter"
          width="100"
          label="二季度"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="threeQuarter"
          width="100"
          label="三季度"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="fourQuarter"
          width="100"
          label="四季度"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="january"
          width="100"
          label="1月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="february"
          width="100"
          label="2月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="march"
          width="100"
          label="3月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="april"
          width="100"
          label="4月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="may"
          width="100"
          label="5月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="june"
          width="100"
          label="6月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="july"
          width="100"
          label="7月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="august"
          width="100"
          label="8月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="september"
          width="100"
          label="9月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="october"
          width="100"
          label="10月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="november"
          width="100"
          label="11月"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="december"
          width="100"
          label="12月"
          show-overflow-tooltip
        >
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="page.pageNum"
      :page-size="page.pageSize"
      layout="total, prev, pager, next, sizes"
      :total="total"
    >
    </el-pagination>

    <el-dialog title="刷新数据" width="300px" :visible.sync="refreshDialogVisible" append-to-body>
      <el-form :model="refreshForm" ref="refreshForm" :rules="refreshFormRules">
        <el-form-item label="日期" prop="acctMonth">
          <el-date-picker
              style="width: 200px;"
              v-model="refreshForm.acctMonth"
              type="month"
              size="mini"
              placeholder="选择年月"
              value-format="yyyyMM"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button
          size="mini"
          type="primary"
          @click="handle_refresh"
        >确定</el-button>
        <el-button size="mini" @click="refreshDialogVisible = false" >取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSessionStorage } from "@/common/js/storage";
import { getCookie } from "@/common/js/cookie";
import { $budgetAPI } from "@/api";
import prefixAPI from "@/api/prefixAPI";
export default {
  name: "budgetDelivery",
  data() {
    return {
      form: {
        year: this.moment().format("yyyy"),
        areaSelect: {
          areaId: "",
          areaLvl: "",
          areaName: "hangzhou",
        },
        recordId: "",
        indexType: "",
      },
      page: {
        pageNum: 1,
        pageSize: 20,
      },
      indexTypeOptions: [
        { value: "收入类", key: 1 },
        { value: "业务量", key: 2 },
      ],
      activeName: "first",
      areaList: [],
      accountInfo: "",
      recordsList: [],
      fileName: "",
      year: this.moment().format("yyyy"),
      isDelete: 1,
      loading: "",
      tableData: [],
      emptyText: "数据加载中...",
      total: 0,

      refreshDialogVisible: false,
      refreshForm: {
        acctMonth: "",
      },
      refreshFormRules: {
        acctMonth: [{ required: true, message:"必填", trigger: "change" }]
      }
    };
  },
  watch: {
    areaSelect: {
      handler(newValue, oldValue) {
        let obj = {
          year: this.form.year,
          areaId: this.form.areaSelect.areaId
            ? this.form.areaSelect.areaId
            : this.accountInfo.areaId,
        };
      },
      deep: true,
    },
  },
  computed: {
    params() {
      let obj = {
        areaId: this.form.areaSelect.areaId
          ? this.form.areaSelect.areaId
          : this.accountInfo.areaId,
        areaName: this.form.areaSelect.areaName
          ? this.form.areaSelect.areaName
          : this.accountInfo.areaName,
        areaLvl: this.form.areaSelect.areaLvl
          ? this.form.areaSelect.areaLvl
          : this.accountInfo.areaLvl,
        year: this.form.year,
      };
      return obj;
    },
    areaSelect() {
      return this.form.areaSelect;
    },
  },
  created() {
    this.init();
  },
  methods: {
    handleCurrentChange(current) {
      this.page.pageNum = current;
      let params = {
        testYear: this.form.year ? this.form.year : this.yearList[0],
        areaId: this.form.areaSelect.areaId
          ? this.form.areaSelect.areaId
          : this.accountInfo.areaId,
        indexType: this.form.indexType ? this.form.indexType : "",
      };
      this.getReleaseShow(params);
    },
    // 导出
    exportData() {
      let params = {
        testYear: this.form.year ? this.form.year : this.yearList[0],
        areaId: this.form.areaSelect.areaId
          ? this.form.areaSelect.areaId
          : this.accountInfo.areaId,
        indexType: this.form.indexType ? this.form.indexType : "",
      };
      let token = getCookie("token");
      // 根据不同模式切换不同的路径
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          `/api/releaseSecond/exportReleaseShow?testYear=${params.testYear}&indexType=${params.indexType}&areaId=${params.areaId}&token=${token}`;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          `/api/releaseSecond/exportReleaseShow?testYear=${params.testYear}&indexType=${params.indexType}&areaId=${params.areaId}&token=${token}`;
      }
    },
    exportDataAll() {
      let params = {
        testYear: this.form.year ? this.form.year : this.yearList[0],
        areaId: this.form.areaSelect.areaId
          ? this.form.areaSelect.areaId
          : this.accountInfo.areaId,
        indexType: this.form.indexType ? this.form.indexType : "",
      };

      let token = getCookie("token");
      // 根据不同模式切换不同的路径
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          `/api/releaseSecond/batchExportReleaseShow?testYear=${params.testYear}&indexType=${params.indexType}&areaId=${params.areaId}&token=${token}`;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          `/api/releaseSecond/batchExportReleaseShow?testYear=${params.testYear}&indexType=${params.indexType}&areaId=${params.areaId}&token=${token}`;
      }
    },
    errorUpload(err, file, fileList) {
      console.log(err);
      this.loading.close();
    },
    progress(event, file, fileList) {
      this.loading = this.$loading({
        lock: true,
        text: "正在导入",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    //导入成功的回调
    importTarget(response, file, fileList) {
      this.alertError(response);
      this.loading.close();
      if (response.code == 0) {
        this.$message({
          type: "success",
          message: "导入成功",
        });
        let obj = {
          year: this.form.year,
          areaId: this.form.areaSelect.areaId
            ? this.form.areaSelect.areaId
            : this.accountInfo.areaId,
          indexType: this.form.indexType ? this.form.indexType : "",
        };
        // this.getReleaseRecordRs(obj);
        this.form.recordId = response.content;
        this.activeName = "first";
        let params = {
          areaId: this.form.areaSelect.areaId
            ? this.form.areaSelect.areaId
            : this.accountInfo.areaId,
          testYear: this.form.year,
          indexType: this.form.indexType ? this.form.indexType : "",
        };
        this.getReleaseShow(params);
      }
    },
    // 模版下载
    exportModal() {
      let token = getCookie("token");
      let areaId = this.form.areaSelect.areaId
        ? this.form.areaSelect.areaId
        : this.accountInfo.areaId;
      let areaLvl = this.form.areaSelect.areaLvl
        ? this.form.areaSelect.areaLvl
        : this.accountInfo.areaLvl;
      // 根据不同模式切换不同的路径
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          "/api/releaseSecond/newDownTemplate?areaId=" +
          areaId +
          "&areaLvl=" +
          areaLvl +
          "&token=" +
          token;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          "/api/releaseSecond/newDownTemplate?areaId=" +
          areaId +
          "&areaLvl=" +
          areaLvl +
          "&token=" +
          token;
      }
    },
    //年份改变清空区域
    changeYear() {
      // this.$refs.cascader.clear()
    },
    //下达按钮是否展示
    recordChange(val) {
      this.recordsList.map((item, index) => {
        if (item.id == val) {
          this.isDelete = item.isDelete;
        }
      });
    },
    // 查询
    search() {
      let params = {
        testYear: this.form.year ? this.form.year : this.yearList[0],
        areaId: this.form.areaSelect.areaId
          ? this.form.areaSelect.areaId
          : this.accountInfo.areaId,
        indexType: this.form.indexType ? this.form.indexType : "",
      };
      this.page.pageNum = 1;
      this.getReleaseShow(params);
    },
    //请求数据
    getReleaseShow(params) {
      this.tableData = [];
      this.emptyText = "数据加载中...";
      let newParams = {
        ...params,
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
      };
      $budgetAPI.getReleaseShow(newParams, (res) => {
        if (res.code == 0) {
          this.tableData = res.content.data.data;
          this.total = res.content.count;
          if (this.tableData.length == 0) {
            this.emptyText = "暂无数据";
          }
        }
      });
    },
    //下达
    // doRelease() {
    //   $budgetAPI.doRelease(
    //     {
    //       recordId: this.form.recordId ? this.form.recordId : '',
    //     },
    //     (res) => {
    //       this.alertError(res)
    //       if (res.code == 0) {
    //         this.$message({
    //           type: 'success',
    //           message: res.message,
    //         })
    //       }
    //     },
    //     (err) => {}
    //   )
    // },
    init() {
      this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
      //获取下达记录列表
      let obj = {
        year: this.form.year,
        areaId: this.form.areaSelect.areaId
          ? this.form.areaSelect.areaId
          : this.accountInfo.areaId,
      };
      // this.getReleaseRecordRs(obj);
      if (this.$route.query.areaId) {
        let query = this.$route.query;
        this.form = {
          year: query.recordYear,
          areaSelect: {
            areaId: query.areaId,
            areaLvl: query.areaLvl,
            areaName: query.areaName,
          },
          // recordId: query.id,
        };
        let params = {
          testYear: this.form.year,
          areaId: this.form.areaSelect.areaId,
        };
        this.getReleaseShow(params);
      } else {
        this.form.areaSelect.areaId = this.accountInfo.areaId;
        this.form.areaSelect.areaLvl = this.accountInfo.areaLvl;
        this.form.areaSelect.areaName = this.accountInfo.areaName;
        setTimeout(() => {
          let params = {
            testYear: this.form.year,
            areaId: this.accountInfo.areaId,
          };
          this.getReleaseShow(params);
        }, 1000);
      }
    },
    //根据层级获取区域树
    getCompanyByLvl() {
      $budgetAPI.getCompanyByLvl(
        {
          lvl: this.accountInfo.areaLvl,
          areaId: this.accountInfo.areaId,
        },
        (res) => {
          this.alertError(res);
          this.areaList = res.content;
        },
        (err) => {}
      );
    },
    //获取下达记录
    getReleaseRecordRs(params) {
      $budgetAPI.getReleaseRecordRs(
        params,
        (res) => {
          this.alertError(res);
          if (res.code == 0) {
            this.recordsList = res.content;
            this.form.recordId = "";
            if (res.content) {
              this.form.recordId = res.content[0].id;
              this.isDelete = res.content[0].isDelete;
            }
          }
        },
        (err) => {}
      );
    },
    //刷新
    async handle_refresh(){
      await this.$refs.refreshForm.validate();
      const Loading = this.$loading({
        lock: true,
        text: "正在刷新",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const { acctMonth } = this.refreshForm;
      $budgetAPI.releaseSecondRefreshData(
        { acctMonth, token: getCookie("token") },
        res => {
          if(res.code == 0){
            this.$message.success("刷新成功");
            this.search();
            this.refreshDialogVisible = false;
            this.$refs.refreshForm.resetFields();
          } else {
            this.$message.error(res.message || "刷新失败");
          }
          Loading.close();
        },
        err => {
          this.$message.error("正在处理中");
          Loading.close();
        }
      )
    }
  },
};
</script>

<style lang="scss" scoped>
.formList {
  display: flex;
  display: -webkit-flex;
  // justify-items: center;
  align-items: center;
  .el-form-item:not(.form-buttons) {
    width: 100%;
    max-width: 285px;
    // /deep/ .el-form-item__content {
    // max-width: 175px;
    // }
  }
  .form-buttons {
    // width: 410px;
    width: 100%;
    margin-left: 10px;
    /deep/ .el-form-item__content {
      display: flex;
      display: -webkit-flex;
      button {
        margin: 0 3px;
      }
    }
  }
}

.budgetDelivery {
  /deep/ .cell {
    text-align: center;
  }
  .table-content {
    .table-header {
      display: flex;
      justify-content: space-between;

      .btn-right {
        display: flex;
      }

      .table-title {
        font-size: 14px;
        font-weight: bold;
        height: 30px;
        line-height: 30px;

        span {
          display: inline-block;
          width: 5px;
          height: 5px;
          background-color: #418ee9;
          border-radius: 1000%;
          overflow: hidden;
          margin-right: 10px;
          margin-bottom: 3px;
        }
      }

      // .upload-demo {
      // margin: 0 15px;
      // }
    }
  }
}
.tableBox {
  margin: 15px 0 10px;
}
</style>



